var stationId = undefined;
var data = undefined;
var filterDataUtil = undefined;
var filterColumnUtil = undefined;
var overhaulTable = (function(){
	var columns = [ localeTitle.XuHao, localeTitle.ShenQingDanWei, localeTitle.GongZuoDiDian, localeTitle.GongZuoZhuangTai,
	                localeTitle.JianXiuNeiRong, localeTitle.KaiShiShiJian, localeTitle.JieShuShiJian, localeTitle.ZhiXingQingKuang ];
	var id = 'overhaulTable';
	var table = undefined;
	var dataset = undefined;
	var ulHeight = document.getElementById("selectUL").offsetHeight; 
	var scrollYHeight = wrapperHeight - ulHeight -140;
	var opt = MyTable.getDefaultOptions();
	opt.paging = false;
	opt.autoWidth = true;
	var defs = [ {
		targets : 0,
		width : '3%'
	}, {
		targets : 1,
		width : '7%'
	}, {
		targets : 2,
		width : '7%'
	}, {
		targets : 3,
		width : '7%'
	}, {
		targets : 4,
		width : '25%'
	}, {
		targets : 5,
		width : '10%'
	}, {
		targets : 6,
		width : '10%',
	}, {
		targets : 7,
		width : '10%',
	} ];
	opt.scrollY = scrollYHeight + "px";
	opt.scrollX = false;
	opt.columnDefs = defs;
	opt.rowCallback = function(row, data, index) {
		var done = data[3];
		if (done.indexOf("待开工") > -1) {
			$(row).addClass('todoRow');
		} else if (done.indexOf("进行中") > -1) {
			$(row).addClass('doingRow');
		} else if (done.indexOf("已完工") > -1) {
			$(row).addClass('doneRow');
		}
	};

	function draw(){
		if (table) {
			table.getTable().destroy();
		}
		table = new MyTable(id, columns, opt);
		table.setDataSet(dataset).show();
	}
	function getDateset(overhauls){
		var datas = [];
		for ( var i in overhauls) {
			var f = overhauls[i];
			var startTime = DateUtil.dateTime(f.startTime);
			var endTime = DateUtil.dateTime(f.endTime);
			datas.push([ Number(i) + 1, str(f.applicantCompany), str(f['station_name']), str(f.done), str(f.content),
			             startTime, endTime, str(f.executiveCondition) ]);
		}
		return datas;
	}
	function str(v){
		return v?v:'';
	}
	function setData(data){
		dataset = getDateset(data);
	}
	function filterColumns(indexs){
		for (var i = 0; i < defs.length; i++) {
			defs[i].bVisible = false;
			for(var j in indexs){
				if(i == indexs[j]){
					defs[i].bVisible = true;
					break;
				}
			}
		}
		draw();
	}
	function getColumns(){
		var cols = [];
		for(var i=0;i<columns.length;i++){
			cols.push({
				name:columns[i],
				visible:defs[i].bVisible
			});
		}
		return cols;
	}
	return {
		setData:function(data){
			setData(data);
		},
		draw:draw,
		filterColumns:function(indexlist){
			filterColumns(indexlist);
		},
		getColumns:getColumns,
	};

})();
var filterStatusUtil = (function(){
	
	var $divs = $("#statusDiv>div");
	var list = [{name:'待开工'},{name:'进行中'},{name:'已完工'}];
	
	$divs.on('click',function(e){
		$target = $(e.currentTarget);
		$('.selectedDiv').removeClass("selectedDiv");
		$target.addClass("selectedDiv");
		
		doFilter(null,getCurrentInfo());
	});
	function getCurrentInfo(){
		var info = {
				selectAll:false,
				selectedItems:[]
		};
		if($($divs[0]).hasClass('selectedDiv')){
			info.selectAll = true;
			info.selectedItems = list; 
		}else{
			for(var i=1;i<$divs.length;i++){
				if($($divs[i]).hasClass('selectedDiv')){
					info.selectedItems.push(list[i-1]);
				}
			}
		}
		return info;
	}
	function setChecked(index){
		$('.selectedDiv').removeClass("selectedDiv");
		$($divs[index]).addClass("selectedDiv");
	}
	
	return {
		getInfo:function(){
			return getCurrentInfo();
		},
		setSelectAll:function(){
			setChecked(0);
		},
		setSelectItem:function(name){
			for(var i=0;i<list.length;i++){
				if(list[i].name == name){
					setChecked(i);
					break;
				}
			}
		},
	};
})();
function init(){
	start = $('#startTime').val();
	end = $('#endTime').val();
	$('#start').val(start);
	$('#end').val(end);

	$('#start').datetimepicker({
		format : 'yyyy-mm-dd',
		minView : 2,
		autoclose : true,
		endDate : new Date(),
		todayHighlight : true
	});
	$('#end').datetimepicker({
		format : 'yyyy-mm-dd',
		minView : 2,
		autoclose : true,
		endDate : new Date(),
		pickerPosition : 'bottom-left',
		todayHighlight : true
	});

	stationId = $('#stationId').val();
	loadData();
}

function query(){
	start = $('#start').val();
	end = $('#end').val();
	$('.selectedDiv').removeClass("selectedDiv");
	$("#allStatus").addClass("selectedDiv");
	$('#selectButton').removeClass("redText");
	loadData();
}
function loadData() {
	var url = "/rest/protectOverhaul/getProtectOverhaulByDate/"+start+"/"+end;
	if(stationId){
		url += "/"+stationId;
	}
	$.getJSON(url, function(result) {
		result.sort(sortOverhaul);
		data = result;
		loadContent();
		loadNum();
	});
}
function sortOverhaul(obj1, obj2) {
	// 先比较待开工，进行中，完工在比较开始时间
	var done1 = getStatusNum(obj1.done);
	var done2 = getStatusNum(obj2.done);
	if (done1 == done2) {
		var t1 = getTime(obj1.startTime);
		var t2 = getTime(obj2.startTime);
		return t1 - t2;
	} else {
		return done1 - done2;
	}
	function getTime(obj1) {
		return obj1 ? obj1.time ? obj1.time : obj1 : 0;
	}
	function getStatusNum(done) {
		var num = 0;
		if (done) {
			if (done.indexOf("待") > -1 || done.indexOf("开") > -1) {
				num = 1;
			} else if (done.indexOf("进行") > -1) {
				num = 2;
			} else if (done.indexOf("已") > -1) {
				num = 3;
			}
		}
		return num;
	}
}
function loadColumnsFilter(){
	if(!filterColumnUtil){
		filterColumnUtil = new CheckboxGroup("selectDiv");
	}
	var columns = overhaulTable.getColumns();
	var items = [];
	for(var i in columns){
		items.push({
			name:columns[i].name,
			value:columns[i].name,
			index:i,
			unselect:columns[i].visible == false
		});
	}
	var opt = [{
		name:localeTitle.LieShaiXuan,
		items:items
	}];
	filterColumnUtil.setOption(opt);
	filterColumnUtil.onChange(doColumnFilter);
	filterColumnUtil.setSelectAllLabel(localeTitle.QuanXuan);
	filterColumnUtil.draw();
}
function loadDataFilter(data){
	if(!filterDataUtil){
		filterDataUtil = new CheckboxGroup("columnsSelectDiv");
	}
	var opt = [];
	if(!stationId){
		var stationFilter = {name:localeTitle.GongZuoDiDian,items:[]};
		opt.push(stationFilter);
		bk:	for(var i in data){
			
			for(var j in stationFilter.items){
				if(stationFilter.items[j].value  == data[i]['station_id']){
					continue bk;
				}
			}
			
			stationFilter.items.push({
				name:data[i]['station_name'],
				value:data[i]['station_id']
			});
		}
	}
	
	filterDataUtil.setOption(opt);
	filterDataUtil.setSelectAllLabel(localeTitle.QuanXuan);
	//触发。之前是怎么触发的
	//改变单个的时候，就触发好了
	filterDataUtil.onChange(doFilter);
	filterDataUtil.draw();
}
function loadStatusFilter(){
	filterStatusUtil.setSelectAll();
}
function doColumnFilter(info) {
	if(!info){
		info = filterColumnUtil.getInfo();
	}
	if(info[0].selectAll){
		$('#columnsSelectButton').removeClass('redText');
	}else{
		$('#columnsSelectButton').addClass('redText');
	}
	var indexlist = [];
	for(var i in info[0].selectedItems){
		indexlist.push(info[0].selectedItems[i].index);
	}
	overhaulTable.filterColumns(indexlist);
}
function doFilter(dataInfo,statusInfo){
	if(!dataInfo && !stationId){
		dataInfo = filterDataUtil.getInfo();
	}
	if(dataInfo){
		if(dataInfo[0].selectAll){
			$('#selectButton').removeClass('redText');
		}else{
			$('#selectButton').addClass('redText');
		}
	}
	if(!statusInfo){
		statusInfo = filterStatusUtil.getInfo();
	}
	//还需要拿到另一个筛选器
	//info有两个，一个是  进行中
	var newData = [];
	for(var i in data){
		var d = data[i];
		var process = 0;
		//需要两个都通过
		if(dataInfo && !dataInfo[0].selectAll){
			for(var j in dataInfo[0].selectedItems){
				if( d['station_id'] == dataInfo[0].selectedItems[j].value){
					process ++;
					break;
				}
			}
		}else{
			process ++;
		}
		if(!statusInfo.selectAll){
			for(var j in statusInfo.selectedItems){
				if( d.done == statusInfo.selectedItems[j].name){
					process ++;
					break;
				}
			}
		}else{
			process ++;
		}
		if(process == 2){
			newData.push(d);
		}
	}
	overhaulTable.setData(newData);
	overhaulTable.draw();
}
function loadContent(){
	if(stationId){
		$('#selectButton').css('display','none');
	}else{
		loadDataFilter(data);
	}
	loadColumnsFilter();
	loadStatusFilter();
	overhaulTable.setData(data);
	overhaulTable.draw();
}
function loadNum(){
	var todo = 0;
	var doing = 0;
	var done = 0;
	for(var i in data){
		var status = data[i].done;
		if(status == '待开工'){
			todo ++;
		}else if(status == '进行中'){
			doing ++;
		}else if(status == '已完工'){
			done ++;
		}
	}
	$('#todoNum').html(todo);
	$('#doingNum').html(doing);
	$('#doneNum').html(done);
	$('#allNum').html(data.length);
}
function onSelectDivClick(){
	if(!stationId){
		var btn = $('#selectButtonIcon');
		btn.toggleClass("fa-caret-down");
		btn.toggleClass("fa-caret-up");
		filterDataUtil.collapse();
	}
	overhaulTable.draw();
}
function onColumnsSelectDivClick(){
	var btn = $('#columnsSelectButtonIcon');
	btn.toggleClass("fa-caret-down");
	btn.toggleClass("fa-caret-up");
	filterColumnUtil.collapse();
	overhaulTable.draw();
}
init();